package util;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Properties;

/**
 * @author caoqianfan
 * @date 2024/7/15 上午10:48
 */
@Slf4j
@Data
public class JDBCUtils {
    private JDBCUtils() {
    }  //构造函数私有化

    private static String driverClass;
    private static String url;
    private static String username;
    private static String password;
    private static Connection con;

    static {
        try {
            InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("application.properties");
            Properties properties = new Properties();
            properties.load(is);
            driverClass = properties.getProperty("datasource.driverClass");
            url = properties.getProperty("datasource.url");
            username = properties.getProperty("datasource.username");
            password = properties.getProperty("datasource.password");
            Class.forName(driverClass);

        } catch (Exception e) {
            log.error(e.getMessage());
        }
    }

    public static Connection getConnection() {  //获取连接对象
        try {
            con = DriverManager.getConnection(url, username, password);
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return con;
    }

    //关闭连接（有查询结果集）
    public static void close(Connection con, Statement stat, ResultSet res) {
        if (con != null) {
            try {
                con.close();
            } catch (Exception e) {
                log.error(e.getMessage());
            }
        }
        if (stat != null) {
            try {
                stat.close();
            } catch (Exception e) {
                log.error(e.getMessage());
            }
        }
        if (res != null) {
            try {
                res.close();
            } catch (Exception e) {
                log.error(e.getMessage());
            }
        }
    }

    //关闭连接（无查询结果集）
    public static void close(Connection con, Statement stat) {
        close(con, stat, null);
    }
}
